package com.heatup.apt.common.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Encoder;

public class ImageUtils {
	//log
	private static final Logger logger = LoggerFactory.getLogger(ImageUtils.class);
	
	public static String imgUtils(String bgImg, String qrImg, String nickName, String money) {
		if(StringUtils.isBlank(bgImg) || StringUtils.isBlank(qrImg)){ //如果有一张图片为空
			return null;
		}
		try {

			URL bgImgUrl = ImageUtils.class.getClassLoader().getResource("image/" + bgImg);
			File bgImgFfile = new File(bgImgUrl.getFile());
			URL qrUrl =  new URL(qrImg);

			BufferedImage qrBuffer = ImageIO.read(qrUrl);// 二维码图
			BufferedImage bgImgBuffer = ImageIO.read(bgImgFfile);// 背景图
			int x = (bgImgBuffer.getWidth() - qrBuffer.getWidth()) / 2; // 获取二维码要放在的位置
			int y = (bgImgBuffer.getHeight() - qrBuffer.getHeight()) / 2 - 300;
			Font aa = new Font("微软雅黑", Font.PLAIN, 40);
			Graphics2D g = bgImgBuffer.createGraphics();
			g.drawImage(qrBuffer, x + 40, y, qrBuffer.getWidth(), qrBuffer.getHeight(), null);
			Color color = new Color(255, 107, 0);
			g.setColor(color);
			g.setFont(aa);
			logger.info("nick_name value is :" + nickName);
			g.drawString(nickName, 135, bgImgBuffer.getHeight() - 1500);
			logger.info("money value is :" + money);
			g.drawString(money, 420, bgImgBuffer.getHeight() - 1370);
			
			Color color2 = new Color(255, 255, 255);
			Font aa2 = new Font("微软雅黑", Font.PLAIN, 30);
			g.setColor(color2);
			g.setFont(aa2);
			g.drawString(money, 215, bgImgBuffer.getHeight() - 1380);
			g.dispose();
			
			ByteArrayOutputStream os = new ByteArrayOutputStream();  
			ImageIO.write(bgImgBuffer, "png", os);  
			InputStream is = new ByteArrayInputStream(os.toByteArray()); 
			
			
//			ImageIO.write(bgImgBuffer, "png", new File("D:/new.png"));
			return GetImageStr(is);
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}

	public static void main(String[] args) {
		File f = new File("d:/new.png");
		f.delete();
		imgUtils("1.png", "2.png", "意难忘", "10");
	}

	// 图片转化成base64字符串
	public static String GetImageStr(InputStream in) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		byte[] data = null;
		// 读取图片字节数组
		try {
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);// 返回Base64编码过的字节数组字符串
	}
}
